﻿using Lights.Types;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Lights.Page
{
    /// <summary>
    /// Logica di interazione per frmImporter.xaml
    /// </summary>
    public partial class frmImporter : Window
    {
        class PreviewContainer
        {
            #region Properties
            public string Name { get; private set; }
            public BitmapSource Thumbnail { get; private set; }
            public int Hashcode { get; private set; }
            public string Path { get; private set; }
            public bool AlreadyImported { get; set; }
            #endregion

            #region Fields
            #endregion

            #region Methods
            public PreviewContainer(string path)
            {
                this.Path = path;
                this.Name = System.IO.Path.GetFileNameWithoutExtension(path);

                // apro l'immagine originale
                byte[] buffer = File.ReadAllBytes(path);

                // calcolo l'hashcode
                int hashcode = 0;
                byte[] hashBuffer = MD5.Create().ComputeHash(buffer);
                for (int i = 0; i < hashBuffer.Length; i += 4)
                {
                    hashcode ^= (hashBuffer[i] | hashBuffer[i + 1] << 8 | hashBuffer[i + 2] << 16 | hashBuffer[i + 3] << 24);
                }

                this.Hashcode = hashcode;

                BitmapImage bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.CreateOptions = BitmapCreateOptions.DelayCreation;
                bmp.CacheOption = BitmapCacheOption.None;
                bmp.DecodePixelWidth = 128;
                bmp.UriSource = new Uri(path, UriKind.Absolute);
                bmp.EndInit();
                bmp.Freeze();

                this.Thumbnail = bmp;
            }
            #endregion
        }

        public object[] SelectedItems { get; private set; }

        private static readonly string[] imgExt = new string[] { "*.jpg", "*.png", "*.bmp" };
        private static readonly object dummyNode = new object();
        private readonly ObservableCollection<PreviewContainer> images = new ObservableCollection<PreviewContainer>();
        private BackgroundWorker worker;

        public frmImporter()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.viewer.ItemsSource = images;
            this.tvFolders.SelectedItemChanged += tvFolders_SelectedItemChanged;

            foreach (string drive in Environment.GetLogicalDrives())
            {
                TreeViewItem item = new TreeViewItem();
                item.Header = drive;
                item.Tag = drive;
                item.FontWeight = FontWeights.Normal;
                item.Items.Add(dummyNode);
                item.Expanded += item_Expanded;
                tvFolders.Items.Add(item);
            }

            worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.ProgressChanged += worker_ProgressChanged;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            worker.WorkerSupportsCancellation = true;
            worker.WorkerReportsProgress = true;
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.infoPanel.Visibility = System.Windows.Visibility.Hidden;
            this.viewer.IsEnabled = true;
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (!(sender as BackgroundWorker).CancellationPending)
            {
                this.images.Add(e.UserState as PreviewContainer);
                prgBar.Value = e.ProgressPercentage;
            }
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                BackgroundWorker worker = sender as BackgroundWorker;
                string[] images = GetImages(e.Argument.ToString());
                for (int i = 0; i < images.Length; i++)
                {
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        break;
                    }
                    PreviewContainer pc = new PreviewContainer(images[i]);
                    pc.AlreadyImported = Global.PhotoCollector.ContainsKey(pc.Hashcode);
                    worker.ReportProgress((int)((double)i / (double)images.Length * 100.0), pc);
                }
                e.Result = true;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }

        string[] GetImages(string folder)
        {
            List<string> images = new List<string>();
            foreach (var ext in imgExt)
            {
                images.AddRange(Directory.GetFiles(folder, ext));
            }
            return images.ToArray();
        }

        void tvFolders_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            images.Clear();

            if(worker.IsBusy)
                worker.CancelAsync();

            new Thread(new ThreadStart(() =>
                {
                    while (worker.IsBusy)
                    {
                        Thread.Sleep(1);
                    }
                    Dispatcher.Invoke(() =>
                        {
                            worker.RunWorkerAsync(((TreeViewItem)e.NewValue).Tag.ToString());
                        });
                })).Start();


            
            this.infoPanel.Visibility = System.Windows.Visibility.Visible;
            this.viewer.IsEnabled = false;
        }

        void item_Expanded(object sender, RoutedEventArgs e)
        {
            TreeViewItem item = (TreeViewItem)sender;
            if (item.Items.Count == 1 && item.Items[0] == dummyNode)
            {
                item.Items.Clear();
                try
                {
                    foreach (string folder in Directory.GetDirectories(item.Tag.ToString()))
                    {
                        DirectoryInfo info = new DirectoryInfo(folder);
                        if (!info.Attributes.HasFlag(FileAttributes.Hidden) && !info.Attributes.HasFlag(FileAttributes.System))
                        {
                            TreeViewItem subItem = new TreeViewItem();
                            subItem.Header = folder.Substring(folder.LastIndexOf("\\") + 1);
                            subItem.Tag = folder;
                            subItem.FontWeight = FontWeights.Normal;
                            subItem.Items.Add(dummyNode);
                            subItem.Expanded += item_Expanded;
                            item.Items.Add(subItem);
                        }
                    }
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message);
                }
            }
        }

        private void cmdImport_Click(object sender, RoutedEventArgs e)
        {
            PreviewContainer[] selected = this.viewer.SelectedItems.Cast<PreviewContainer>().Where( pc => !pc.AlreadyImported).ToArray();
            string[] paths = new string[selected.Length];
            
            Parallel.For(0, selected.Length, (i) =>
                {
                    paths[i] = selected[i].Path;
                });
            
            this.SelectedItems = paths;

            this.DialogResult = true;
            this.Close();
        }

        private void cmdCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (worker != null && worker.IsBusy)
                worker.CancelAsync();
        }
    }
}
